// import qs from 'qs';

module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		config.timeout = 10000
		// config.baseURL = 'http://192.168.1.3:80'
		config.baseURL = 'http://123.249.12.91:80'
		return config
	})
	
	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => {
		// console.log(config)
		if(!config.custom?.noauth && !vm.$store.state['user_token']){
			uni.reLaunch({ url: '/pages/auth/login' })
			return Promise.reject({status: 401, message: 'Token 验证失败！'})
		}
		config.data = config.data || {}
		// if(config.method == 'POST') config.data = qs.stringify(config.data)
		config.header['Content-Type'] = 'application/x-www-form-urlencoded'
		config.header['Authorization'] = vm.$store.state['user_token']
		return config
	}, err => {
		// console.log(err)
		return Promise.reject(err)
	})
		
	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		// console.log(response)
		const data = response.data
		const custom = response.config?.custom
		if(data.status){
			// Token 验证失败
			if(data.status === 401) return uni.reLaunch({ url: '/pages/auth/login' })
			if(custom.failToast !== false){
				uni.$j.toast(data.message)
			}
			// 进入 catch
			return Promise.reject(data)
		}
		if(custom.successToast !== false){
			uni.$j.toast(data.message)
		}
		return data.data === undefined ? {} : data.data
	}, err => {
		if(err.errMsg == 'request:fail abort statusCode:-1 timeout') return uni.$j.toast('请求超时，请检查网络后重试')
		return Promise.reject(err)
	})
}